package com.ssy.lingxi.open.api.serviceImpl;

import cn.hutool.core.bean.BeanUtil;
import com.ssy.lingxi.common.constant.Constants;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.utils.Aes128Util;
import com.ssy.lingxi.common.utils.PasswordUtil;
import com.ssy.lingxi.common.utils.TokenUtil;
import com.ssy.lingxi.component.redis.service.IRedisUtils;
import com.ssy.lingxi.open.api.entity.User;
import com.ssy.lingxi.open.api.model.response.UserResponse;
import com.ssy.lingxi.open.api.repository.UserRepository;
import com.ssy.lingxi.open.api.service.IUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 用户管理实现类
 * @author jw.chen
 * @version 2.0.0
 * @date 2021/10/12
 */
@Service
public class UserServiceImpl implements IUserService {

    @Resource
    private UserRepository userRepository;

    @Resource
    private IRedisUtils redisUtils;

    /**
     * 超时时长(默认7天)
     */
    public static final long TOKEN_EXPIRE = 7 * 24 * 60 * 60;

    /**
     * 用户登录
     * @param account 账号
     * @param password 密码
     */
    @Override
    public UserResponse login(String account, String password){
        try{
            String pass = PasswordUtil.instance().passwordToMd5String(Aes128Util.aesDecrypt(password));
            User user = userRepository.findFirstByAccountAndPassword(account, pass);
            if(user != null){
                UserResponse userResponse = BeanUtil.copyProperties(user, UserResponse.class);
                String token;
                try {
                    token = TokenUtil.instance().getToken();
                    Boolean flag = redisUtils.set(token, user, TOKEN_EXPIRE, Constants.REDIS_OPEN_API_INDEX);
                    if(flag){
                        userResponse.setToken(token);
                        return userResponse;
                    }
                } catch (Exception e) {
                    throw new BusinessException(ResponseCode.SERVICE_ERROR);
                }
                throw new BusinessException(ResponseCode.SERVICE_ERROR);
            }else{
                throw new BusinessException(ResponseCode.USER_ACCOUNT_OR_PASSWORD_INCORRECT);
            }
        }catch (Exception e){
            throw new BusinessException(ResponseCode.USER_ACCOUNT_OR_PASSWORD_INCORRECT);
        }
    }

}

